/*--------------------------------------------------------------------------
 DEPUI-GFX-TK 3.0 - GPL portable source code libraries 
 http://www.deleveld.dds.nl/depui.htm
 See file docs/copying for copyright details
 ---------------------------------------------------------------------------*/

#define MXMODULE_THEME_ROUNDED
#define MXMODULE_FONT_ALL
#define MXMODULE_SYSMENU

#define MXMODULE_FONTSEL
#include "depui/depui.c"

typedef struct APP {
	union {
		MX_WIN_DATA win;
		MX_TEXTUAL_DATA textual;
		MX_OBJ_DATA obj;
		MX_RECTATOM_DATA rectatom;
		MX_ATOM atom;
	} base;
	MX_BUTTON choose;
	MX_TEXTUAL filename;
} APP;

static void handler(MX_WIN * win)
{
	APP *app = (APP *) win;

	/* Start the file selector to choose a filename */
	if ((mx.event == MX_SELECT) && (mx.data)
		&& (MXOBJ(mx.obj) == MXOBJ(&app->choose))) {
		MX_FONTSEL *fontsel = mx_fontselwin(0, 0, 0, 0);

		mx_modal(fontsel);
		mx_fontsel_refresh(fontsel);

		mx_defaultrect(fontsel, 0);
		mx_layout(fontsel, MX_LAYOUT_CENTER, (MX_OBJ *)0, 0, 0);
		mx_geometry(fontsel);

		mx_win_dirty(fontsel);
		return;

		/* When a filename has been chosen, copy the text for the button */
	} else if (mx.event == MX_FONTSEL_OK) {
		MX_GUIFONT *font = mx_fontsel_info(0);

		/* Make a copy of the filename text */
		if (font) {
			char *text;
			const char *name = mx_guifont_text(font);

			mx_guifont_default(font);

			text = mx_malloc(strlen(name) + 1);
			assert(text);
			strcpy(text, name);

			/* Change the text to be displayed */
			mx_text_set(&app->filename, text, -1, mx_free);
			mx_defaultrect(&app->filename, 0);
			mx_geometry(&app->filename);
			mx_dirty(&app->filename, true);
		}
	}

	mx_win_handler(win);
}

static APP *newapp(void)
{
	/* Create the window for the app */
	APP *app = (APP *) mx_win((MX_WIN *)0, sizeof(APP), handler, 0);

	if (app) {
		/* Make the button */
		mx_button(&app->choose, 0, app, 0);
		mx_text_set(&app->choose, "choose", -1, 0);
		mx_defaultrect(&app->choose, 0);

		/* Make the filename text */
		mx_textual(&app->filename, 0, app, 0);
		mx_text_set(&app->filename, "No font chosen", -1, 0);
		mx_defaultrect(&app->filename, 0);

		/* Place the button and text */
		mx_move(&app->choose, 5, 5);
		mx_layout(&app->filename, (MX_LAYOUT) (MX_LAYOUT_X1 | MX_LAYOUT_BOTTOM),
				  &app->choose, 0, 5);
	}
	return app;
}

int main(int argc, char *argv[])
{
	APP *app;

	(void) argc;
	(void) argv;

	if (!mx_start())
		return EXIT_FAILURE;

	mx_sysmenu();

	app = newapp();
	assert(app);

	mx_position(app, 50, 50, 200, 250);
	mx_text_set(app, "Font and filename test", -1, 0);
	mx_geometry(app);

	return mx_execute();
}
